package com.picture.controller;

import com.picture.result.Result;
import com.picture.utils.AliOssUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.SecureRandom;

@RestController
@RequestMapping("/picture/common")
@Api(tags = "通用类相关接口")
@Slf4j
@CrossOrigin
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping("/upload")
    public Result<String> upload( MultipartFile file){
        String upload = null;
        String fileName = file.getOriginalFilename();

        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;


        try {
             upload = aliOssUtil.upload(file.getBytes(), finalFileName);

        } catch (IOException e) {
            log.info("文件上传失败",e);
        }
        return Result.success(upload);
    }

    @Transactional
    @DeleteMapping("/delete")
    public Result delete(@RequestBody String[] fileurls){
        for (String fileurl:fileurls) {
            aliOssUtil.deleteFile(fileurl);
        }
        return Result.success();
    }
}

